//
//  WBMainViewController.swift
//  XtWeiBo
//
//  Created by 徐腾 on 2017/7/18.
//  Copyright © 2017年 徐腾. All rights reserved.
//

import UIKit

class WBMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupChildController()
        
        setupComposeButton()
    }

    // 使用 @objc private 保护函数，同时允许按钮调用
    func addButtonClick () {
        print("撰写微博")
        
        let vc = UIViewController()
        
        let nav = UINavigationController(rootViewController: vc)
        
        self.present(nav, animated: true, completion: nil)
    }
    
    
    // 中间的加号按钮
    lazy var addComposeButton : UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
    /**
     portrait    : 竖屏，肖像
     landscape   : 横屏，风景画
     
     - 使用代码控制设备的方向，好处，可以在在需要横屏的时候，单独处理！
     - 设置支持的方向之后，当前的控制器及子控制器都会遵守这个方向！
     - 如果播放视频，通常是通过 modal 展现的！
     */
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
}

extension WBMainViewController {
    
    // 添加中间的加号按钮
    func setupComposeButton() {
        
        tabBar.addSubview(addComposeButton)
        
        let w = tabBar.bounds.width / CGFloat(childViewControllers.count) - 1
        
        // insetBy 相当于OC CGRectInset 正数向内缩进，负数向外扩展
        addComposeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        addComposeButton.addTarget(self, action: #selector(addButtonClick), for: .touchUpInside)
    }
    
    
    /// 设置子控制器
    func setupChildController() {
        
        // 先去沙盒里面看是否有 json文件
        let docDior = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        var jsonPath = (docDior as NSString).appendingPathComponent("main.json")
        
        // 加载 data
        var data = try? Data(contentsOf: URL(fileURLWithPath: jsonPath))
        
        // 判断 data 是否是nil
        if data == nil {
            // 从 Bundl 里面加载 json
            jsonPath = Bundle.main.path(forResource: "main.json", ofType: nil)!
            data = try? Data(contentsOf: URL(fileURLWithPath: jsonPath))
        }
        
        // 从bundle 里面 获取json数据
        guard let array = try! JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: Any]]
            
            else {
            return
        }
        
        // 检验存储的 json 的格式是否正确
        // (array as NSArray).write(toFile: "/Users/xuteng/Desktop/demo.plist", atomically: true)
        // 将数组转成 json 需要序列化
        // let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
        // (data as NSData).write(toFile: "/Users/xuteng/Desktop/demo.json", atomically: true)
        
        var arrayM = [UIViewController]()
        
        // 遍历数组，取出字典
        for dict in array {
            // 通过字典，创建控制器
            let vc = controllerWithDict(dict: dict)
            arrayM.append(vc)
        }
        
        viewControllers = arrayM
    }
    
    
    /// 通过字典创建一个子控制器
    ///
    /// - Parameter dict: 信息字典
    /// - Returns: 返回控制器
    private func controllerWithDict (dict:[String: Any]) -> UIViewController {
        
        // 通过字典取出信息， 因为字典返回的字段是可选的，所以可以用guard else守护
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
        let visitorDict = dict["visitorDict"] as? [String: String]
        
        else {
            return UIViewController()
        }
        
        // 创建控制器
        let vc = cls.init()
        
        // 给访客视图信息字典赋值
        vc.visitorInfoDict = visitorDict
        
        vc.title = title
        
        // 设置图片
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        // 设置标题字体的颜色和大小
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.orange],
            for: .selected)
        // 设置大小必须要设置normal状态，其他状态没有用  默认是12号字体
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName : UIFont.systemFont(ofSize: 12)],
            for: .normal)
        
        
        let nav = WBNavigationController(rootViewController: vc)
        
        return nav
    }
    
}
